#include "SKB.h"
#include "global.h"
#include "kernel.h"

int add_to_skb(tju_tcp_t* sock , const void* buffer , int len){
    char* data = malloc(len);
    memcpy(data, buffer, len);
    while (1){
        printf("attemp to add skb \n");
        if(sock -> send_buf_head -> send_buffer_size + len <= TCP_SENDBUF_SIZE){
            SKB_NODE* new_skb_node = (SKB_NODE*)malloc(sizeof(SKB_NODE));
            new_skb_node -> next = NULL;
            new_skb_node -> len = len;
            new_skb_node -> data = data;

            sock -> send_buf_head -> send_buffer_tail -> next = new_skb_node;
            sock -> send_buf_head -> send_buffer_tail = new_skb_node;
            sock -> send_buf_head -> send_buffer_size += len;

            return len;
        }
    }
}

void* send_thread_func(void* arg){
    #ifdef DEBUG_SEND_THREAD
        printf("arg 地址 ： %p \n",arg);
        printf("发送线程建立完成\n");
        int sock_index = *((int*)arg);
        printf("绑定的socket的hash是：%d \n",sock_index);
    #endif

    tju_tcp_t* this_sock;
    if(listen_socks[sock_index] != NULL)
    {   
        #ifdef DEBUG_SEND_THREAD
            printf("绑定监听socket\n");
        #endif
        this_sock = listen_socks[sock_index];
    }
    else if (established_socks[sock_index] != NULL)
    {
        #ifdef DEBUG_SEND_THREAD
            printf("绑定建立socket\n");
        #endif
        this_sock = established_socks[sock_index];
    }
    else{
        printf("此发送线程的sokcet未注册\n");
        exit(-1);
    }

    SKB_HEAD* this_head = this_sock -> send_buf_head;
    while (1) //循环发送SKB的内容
    {
        if(this_head -> wait_to_send -> len +  this_head ->send_not_ack_size <= this_head  -> window_size ){
                sendToLayer3(this_head -> wait_to_send -> data , this_head -> wait_to_send -> len);
                this_head -> send_not_ack = this_head -> wait_to_send;
                this_head -> send_not_ack_size += this_head -> wait_to_send -> len;
                this_head -> send_not_ack_size += this_head -> total_send_size;
                this_head -> wait_to_send = this_head -> wait_to_send -> next;
        }
    }
}

